﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using GameLogic.Controls;

namespace GameLogic.Logic
{
    // Provides basic functionality for a behavior depending on the GameLoop Behavior
    public abstract class GameLoopBehavior<T> : Behavior<T> where T : FrameworkElement
    {
        private GameLoopFinder gameLoopFinder;
        private bool loaded;

        public FrameworkElement Element
        {
            get { return this.AssociatedObject; }
        }

        protected GameLoop GameLoop
        {
            get
            {
                return this.gameLoopFinder.GameLoop;
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.gameLoopFinder = new GameLoopFinder(this.AssociatedObject);
            this.gameLoopFinder.OnGameLoopLoaded += this.OnGameLoopLoaded;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.gameLoopFinder = null;
        }

        private void OnGameLoopLoaded(object sender, EventArgs e)
        {
            if (!this.loaded)
            {
                this.OnGameLoopInitialized();
                this.loaded = true;
            }
        }

        protected virtual void OnGameLoopInitialized()
        {
        }
    }
}

